package com.qf.air.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.qf.air.entity.Air;
import com.qf.air.service.AirService;
import com.qf.air.util.ElasticsearchUtil;
import com.qf.air.util.JSONUtil;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: llf
 * @Date: 2021/11/4 21:02
 */
@Service
public class AirServiceImpl implements AirService {

    private String index = "air";

    @Autowired
    private RestHighLevelClient client;

    @Override
    public Object[] findByPageAndDistrictId(Integer page, Integer rows, Integer districtId, String monitoringStation, Object longStart, Object longEnd) throws ParseException {
        SearchRequest request = new SearchRequest();
        request.indices("air");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        sourceBuilder.size(1000);
        if(districtId != null && districtId != 0){
            boolQueryBuilder.must(QueryBuilders.termQuery("districtId", districtId));
        }
        if(!StringUtils.isEmpty(monitoringStation)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("monitoringStation",monitoringStation));
            HighlightBuilder builder = new HighlightBuilder();
            builder.preTags("<span style='color:red'>");
            builder.postTags("</span>");
            builder.field("monitoringStation");
            sourceBuilder.highlighter(builder);
        }
        if(longStart != null){
            SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
            Date startTime = format.parse(format.format(longStart));
            boolQueryBuilder.must(QueryBuilders.rangeQuery("monitorTime").gte(startTime));
        }
        if(longEnd != null){
            SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
            Date endTime = format.parse(format.format(longEnd));
            boolQueryBuilder.must(QueryBuilders.rangeQuery("lastModifyTime").lte(endTime));
        }
        sourceBuilder.query(boolQueryBuilder);
        request.source(sourceBuilder);
        SearchResponse resp = null;
        try {
            resp = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        List<Air> airs = new ArrayList<>();
        for (SearchHit hit : resp.getHits().getHits()) {
            String json = hit.getSourceAsString();
            Air air = JSONUtil.json2Obj(json, Air.class);

            airs.add(air);
            HighlightField field = hit.getHighlightFields().get("monitoringStation");
            if(field != null){
                String value = field.getFragments()[0].toString();
                air.setMonitoringStation(value);
            }
        }
        return airs.toArray();
    }

    @Override
    public void save(Air air) {
        IndexRequest request = new IndexRequest();
        request.index(index);
        request.source(JSONUtil.obj2JSON(air), XContentType.JSON);
        try {
            IndexResponse resp = ElasticsearchUtil.getClient().index(request, RequestOptions.DEFAULT);
            if ("CREATED".equalsIgnoreCase(resp.getResult().getLowercase())) {
                System.out.println("添加文档成功！");
            }else{
                System.out.println("文档添加失败！");
            }
        } catch (IOException e) {
            System.out.println("文档添加失败"+e.getMessage());
        }
    }

    @Override
    public void deleteById(Integer id) {
        //默认删除文档id
//        DeleteRequest request = new DeleteRequest();
//        request.index(index);
//        request.(String.valueOf(id));
        //自定义删除
        DeleteByQueryRequest request = new DeleteByQueryRequest();
        request.indices(index);
        request.setQuery(QueryBuilders.termQuery("id",id));
        try {
            BulkByScrollResponse response = ElasticsearchUtil.getClient().deleteByQuery(request, RequestOptions.DEFAULT);
//            System.out.println(response);
        } catch (IOException e) {
            System.out.println("文档删除失败"+e.getMessage());
        }
    }

    @Override
    public void updateById(Air air) {
        UpdateRequest request = new UpdateRequest();
        request.index(index);
        request.id(String.valueOf(air.getId()));
        request.doc(JSONUtil.obj2JSON(air),XContentType.JSON);
        try {
            UpdateResponse response = ElasticsearchUtil.getClient().update(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            System.out.println("文档修改失败"+e.getMessage());
        }
    }
}
